package com.example.concurrency.spinLock;

import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 实现一个自旋锁例子
 */
public class SpinLockDemo
{
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public void getLock()
    {
        Thread thread = Thread.currentThread();
        while (!atomicReference.compareAndSet(null, thread))
        {
            System.out.println(String.format("thread{%s} get lock failure,continue!", thread.getName()));
        }
        System.out.println(String.format("thread{%s} get lock success!", thread.getName()));
    }

    public void unLock()
    {
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread, null);
        System.out.println(String.format("thread{%s} release lock success!", thread.getName()));
    }

    public static void main(String[] args)
    {
        SpinLockDemo spinLockDemo = new SpinLockDemo();
        new Thread("线程1")
        {
            @Override
            public void run()
            {
                spinLockDemo.getLock();
                try
                {
                    Thread.sleep(5 * 1000);
                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                spinLockDemo.unLock();
            }
        }.start();

        new Thread("线程2")
        {
            @Override
            public void run()
            {
                try
                {
                    Thread.sleep(1000);
                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                spinLockDemo.getLock();
                spinLockDemo.unLock();
            }
        }.start();
    }
}
